package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.RefreshViewUtils;
import com.sdk.devicemanager.LTEcon;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

public class GprsActivity extends Activity implements View.OnClickListener {
    private TextView mTvTipInfo;
    private TextView mTvSsi;
    private TextView mTvIpDns;
    private TextView mTvNetResult;
    private Button mBtnStart4g;

    LTEcon mLtecon;
    TelephonyManager mTelephonyManager;
    ConnectivityManager connectionManager;
    private static final int TEST_COUNT=100;

    //声明socket
    Socket socket = null;
    //发送一次数据耗时
    long sendTime;
    long usedTime;
    //记录发送成功次数
    int sendSuccCount;
    int sendFailCount;
    private Thread mThread;
    private boolean destroyed;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("result",true);
                    mIntent.putExtras(bundle);
                    GprsActivity.this.setResult(Contants.TEST_ITEM_GPRS,mIntent);
                    finish();
                    break;
            }
        }
    };

    PhoneStateListener mPhoneStateListener = new PhoneStateListener() {

        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            super.onServiceStateChanged(serviceState);
        }

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            try {
                Method getDbm=signalStrength.getClass().getMethod("getDbm");
                int dbm= (int) getDbm.invoke(signalStrength);
                if (Math.abs(dbm)<120) {
                    mTvSsi.setText("4G当前信号强度：" + dbm + "dBm ");
                } else {
                    mTvSsi.setText("4G未连接无信号");
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    };

    private void init() {
        //关闭飞行模式
//        Intent var1;
//        (var1 = new Intent("com.android.action.ltc.mobileData")).putExtra("enable", 1);
//        var1.setComponent(new ComponentName("com.android.settings", "com.android.settings.kby.LtcPowerReceiver"));
//        sendBroadcast(var1);
        mLtecon = new LTEcon(this);
        mBtnStart4g = (Button) findViewById(R.id.btn_start_4g);
        mTvTipInfo = (TextView) findViewById(R.id.tv_4g_tip_info);
        mTvSsi = (TextView) findViewById(R.id.tv_4g_ssi);
        mTvIpDns = (TextView) findViewById(R.id.tv_4g_ip_dns);
        mTvNetResult = (TextView) findViewById(R.id.tv_4g_net_result);
        mBtnStart4g.setOnClickListener(this);
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //获取网络连接管理者
        connectionManager = (ConnectivityManager)
                GprsActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
        mTelephonyManager.listen(mPhoneStateListener,
                PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
                        | PhoneStateListener.LISTEN_SERVICE_STATE);
        WifiManager wifiManager = (WifiManager) getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_gprs);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("cly", "onDestroy");
        destroyed = true;

        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
        if (mLtecon != null) {
            mLtecon.poweroff();
        }

    }

    @Override
    public void onClick(View v) {
        if (v == mBtnStart4g) {
            sendSuccCount=0;
            sendFailCount=0;
            mTvSsi.setText("");
            mTvTipInfo.setText("");
            mTvIpDns.setText("");
            mTvNetResult.setText("");
            mThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //上电
                    RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,false);
                    RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上电中...请等待");
                    int powerState = mLtecon.powerstate();
                    int poweron = 0;
                    if (powerState == 0) {
                        poweron = mLtecon.poweron(20);
                    }
                    Log.e("cly", "powerOn=" + poweron);
                    if (poweron == 0) {
                        Log.e("cly", "上电成功");
                        RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上电成功");
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //打开数据
                        RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上网拨号中...请等待");
                        int mobile_sate = mLtecon.mobile_state();
                        Log.e("cly", "数据连接状态=" + mobile_sate);
                        int mobile_up = 0;
                        if (mobile_sate!=1) {
                            mobile_up = mLtecon.mobile_up(20);
                        }

                        Log.e("cly", "mobile_up=" + mobile_up);
                        if (mobile_up == 0) {
                            Log.e("cly", "数据连接打开");
                            RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "拨号成功");
                            //获取IP
                            String gprsIp = mLtecon.getIP();
                            if (gprsIp != null && gprsIp.length() > 0) {
                                RefreshViewUtils.setText(GprsActivity.this,mTvIpDns, gprsIp);
                            } else {
                                RefreshViewUtils.setText(GprsActivity.this,mTvIpDns, "IP-->null");
                            }
                            List<String> dnss = mLtecon.getDNS();
                            String dnsStr = "";
                            for (int i = 0; i < dnss.size(); i++) {
                                dnsStr += "\r\nDNS" + (i + 1) + ": " + dnss.get(i);
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //获取DNS网络制式
                            RefreshViewUtils.setText(GprsActivity.this,mTvIpDns, "IMSI:" + mLtecon.getcardIMSI()
                                    + "\n网络制式:" + mLtecon.getZS() +
                                    "\n是否漫游:" + mLtecon.isNetworkRoaming() +
                                    "\n运营商:" + mLtecon.getProvidersName() +
                                    dnsStr + "\nIP:" + gprsIp);
                            //连接服务器
                            boolean con = conService();
                            if (con) {
                                Log.e("cly", "连接服务器成功");
                                RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "连接服务器成功");
                                //发送数据
                                sendData();
                            } else {
                                Log.e("cly", "连接服务器失败");
                                RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "连接服务器失败");
                                mLtecon.poweroff();
                                RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);
                            }
                        } else {
                            RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "拨号失败,错误码：" + mobile_up);
                            mLtecon.poweroff();
                            RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);
                        }
                    } else {
                        RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上电失败，错误码:" + poweron);
                        mLtecon.poweroff();
                        RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);

                    }
                }
            });
            mThread.start();
        }
    }

    private boolean conService() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress("120.79.19.49", 6669), 5000);
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            return socket.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void sendData() {
        try {
            sendTime = 0;
            usedTime = 0;
            sendSuccCount = 0;
            sendFailCount = 0;
            String str = "abcdefghijklmnopqrstuvwxy";
            String str2 = null;
            for (int i = 0; i < 40; i++) {
                str2 += str;
            }
            //发送数据
            sendTime = SystemClock.elapsedRealtime();
            for (int j = 0; j < TEST_COUNT; j++) {
                if (destroyed) {
                    return;
                }
                if (socket.isConnected() && !socket.isClosed()) {
                    OutputStream osSend = socket.getOutputStream();  //发送byte字节数据
                    InputStream isRead = socket.getInputStream();
                    osSend.write(((str2 + jy(str)).substring(4)).getBytes());  //写byte字节数据
                    //准备接收服务器反馈dateok
                    String sendResult = "";
                    // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
                    long startSendTime = SystemClock.elapsedRealtime();
                    while (true) {
                        if (destroyed) {
                            return;
                        }
                        if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                            break;
                        }
                        if (isRead.available() > 0) {
                            break;
                        }
                    }
                    byte[] sendBuf = new byte[isRead.available()];
                    isRead.read(sendBuf);
                    sendResult = new String(sendBuf);
                    if (sendResult.equals("dateok")) {
                        sendSuccCount++;
                    } else {
                        sendFailCount++;
                    }
                }
                //至此，发送数据到服务器，服务器返回dateok
                usedTime += (SystemClock.elapsedRealtime() - sendTime);//总耗时
                sendTime = SystemClock.elapsedRealtime();
                RefreshViewUtils.setText(GprsActivity.this,mTvNetResult, "[(成功：" + sendSuccCount
                        +"/失败"+sendFailCount+")/"+TEST_COUNT+"]\r\n总耗时：" + usedTime + "毫秒");
            }
            //断开服务器
            try {
                socket.close();
                RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "已断开服务器");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //挂断
        RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上网挂断中...请等待");
        int mobile_down = mLtecon.mobile_down();
        if (mobile_down == 0) {
            RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "上网挂断成功");
        } else {
            RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "挂断失败,错误码：" + mobile_down);
            mLtecon.poweroff();
            RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);
            return;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //下电
        RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "下电中...");
        int off = mLtecon.poweroff();
        if (off == 0) {
            RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);
            RefreshViewUtils.setText(GprsActivity.this,mTvSsi, "");
            if(sendSuccCount==TEST_COUNT){
                RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "测试成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         Contants.showDailog(GprsActivity.this,
                            "测试成功，是否保存",handler, Gravity.TOP);
                    }
                });
            }else {
                RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "测试失败");
            }
            return;
        } else {
            RefreshViewUtils.setText(GprsActivity.this,mTvTipInfo, "下电失败，错误码:" + off);
            RefreshViewUtils.enableView(GprsActivity.this,mBtnStart4g,true);
            return;
        }
    }

    public int jy(String str)//校验码
    {
        byte[] bytesB = str.getBytes();
        int sum = 0;//求和
        for (int j = 0; j < 40; j++) {
            for (int i = 0; i < bytesB.length; i++) {
                sum += bytesB[i];
            }
        }
        int jiaoyanma = sum % 10000;//那么和10000取余就可以得到后四位
        if (jiaoyanma < 1000) {//当小于四位数的时候，就每次给他乘以10也就是在末尾添0
            jiaoyanma *= 10;
        }
        return jiaoyanma;
    }
}
